package com.ai.imagetext.repository;

import com.ai.imagetext.entity.Tag;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface TagRepository extends JpaRepository<Tag, Long> {
    
    /**
     * 根据标签名查找标签
     */
    Optional<Tag> findByNameAndIsDeletedFalse(String name);
    
    /**
     * 查找所有未删除的标签
     */
    List<Tag> findByIsDeletedFalseOrderByUsageCountDesc();
    
    /**
     * 根据分类查找标签
     */
    List<Tag> findByCategoryAndIsDeletedFalse(String category);
    
    /**
     * 根据标签名模糊搜索
     */
    List<Tag> findByNameContainingAndIsDeletedFalse(String name);
    
    /**
     * 获取热门标签（按使用次数排序）
     */
    Page<Tag> findByIsDeletedFalseOrderByUsageCountDesc(Pageable pageable);
    
    /**
     * 获取最新标签
     */
    Page<Tag> findByIsDeletedFalseOrderByCreatedAtDesc(Pageable pageable);
    
    /**
     * 根据使用次数范围查找标签
     */
    List<Tag> findByUsageCountBetweenAndIsDeletedFalse(Integer minCount, Integer maxCount);
    
    /**
     * 统计未删除的标签数量
     */
    long countByIsDeletedFalse();
    
    /**
     * 根据分类统计标签数量
     */
    long countByCategoryAndIsDeletedFalse(String category);
    
    /**
     * 更新标签使用次数
     */
    @Modifying
    @Query("UPDATE Tag t SET t.usageCount = t.usageCount + :increment, t.updatedAt = CURRENT_TIMESTAMP WHERE t.id = :id")
    void updateUsageCount(@Param("id") Long id, @Param("increment") Integer increment);
    
    /**
     * 软删除标签
     */
    @Modifying
    @Query("UPDATE Tag t SET t.isDeleted = true, t.updatedAt = CURRENT_TIMESTAMP WHERE t.id = :id")
    void softDeleteById(@Param("id") Long id);
    
    /**
     * 获取标签分类统计
     */
    @Query("SELECT t.category, COUNT(t) FROM Tag t WHERE t.isDeleted = false GROUP BY t.category")
    List<Object[]> getCategoryStatistics();
    
    /**
     * 查找或创建标签
     */
    @Query("SELECT t FROM Tag t WHERE t.name = :name AND t.isDeleted = false")
    Optional<Tag> findOrCreateByName(@Param("name") String name);
}